<template>
  <div class="page-container" v-loading="loading">
    <div class="page-content">
      <div class="panel-container panel1">
        <el-form ref="elForm" :model="formData" :rules="rules" size="mini" label-width="120px">
          <el-row :gutter="100">
            <el-col :span="12">
              <el-form-item label="信息UUID:">{{ formData.id }}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="拍卖名称:" prop="title">
                <el-input v-model="formData.title" placeholder="请输入拍卖名称" clearable :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属地区:" prop="city_ids">
                <el-cascader v-model="areaSelected" :options="areaList" style="width: 100%" :props="{ checkStrictly: true, value: 'code', label: 'name' }" @change="handleAreaChange" clearable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="信息介绍:" prop="desc">
                <!-- <tinymce ref="tinymce" v-model="formData.desc" placeholder="请输入" :height="500" infoType="notice" :key="'innerNoticePublish' + tinymceFlag"></tinymce> -->
                <TinyMCE ref="tinymce" v-model="formData.desc" :height="800" infoType="notice" :key="'innerNoticePublish' + tinymceFlag" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="fixed-container">
      <div class="fixed-content">
        <div class="panel-container panel2">
          <div class="panel-content" v-if="editModel === 'add'">
            <el-button size="mini" @click="handleClose">取消</el-button>
            <el-button size="mini" type="primary" @click="handleSubmit">发布</el-button>
            <el-button size="mini" type="primary" @click="handleSubmit('next')">发布并新增下一条</el-button>
          </div>
          <div class="panel-content" v-if="editModel === 'edit'">
            <el-button size="mini" @click="handleClose">取消</el-button>
            <el-button size="mini" type="danger" @click="handleDelete">删除</el-button>
            <el-button size="mini" type="primary" @click="handleSubmit">发布</el-button>
            <el-button size="mini" type="primary" @click="handleSubmit('next')">发布并编辑下一条</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { apiInnerDetail, apiInnerAdd, apiInnerEdit, apiInnerEditGetNext, apiInnerDel } from '@/api/biddingNotice'
// import tinymce from '@/components/Tinymce'
import TinyMCE from '@/components/TinyMCE7'

export default {
  name: 'InnerNoticePublish',
  components: { TinyMCE },
  props: [],
  data() {
    return {
      tinymceFlag: 1,
      queryId: '',
      tableQuery: {},
      loading: false,
      editModel: 'add',
      formData: {
        title: '',
        desc: '',
        sheng_id: '',
        shi_id: '',
      },
      rules: {
        title: [{ required: true, message: '请输入拍卖名称', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入信息介绍', trigger: 'blur' }],
      },
      // 临时变量
      areaSelected: '',
      areaList: [],
    }
  },
  computed: {},
  watch: {},
  activated() {
    this.tinymceFlag++
  },
  mounted() {
    this.init()
  },
  methods: {
    // 初始化
    init() {
      this.getSelectList()
      this.queryId = this.$route.query.id
      if (this.queryId) {
        this.editModel = 'edit'
        const tableQuery = window.localStorage.getItem('inner-notice-edit-table-query')
        if (tableQuery) {
          this.tableQuery = JSON.parse(tableQuery)
          this.tableQuery.position++
          this.tableQuery.is_next = 1
        } else {
          this.tableQuery = {}
          this.tableQuery.position = 1
          this.tableQuery.is_next = 1
        }
        this.getDetail()
      } else {
        this.editModel = 'add'
      }
    },
    // 获取详情
    getDetail() {
      this.loading = true
      apiInnerDetail({ id: this.queryId })
        .then((res) => {
          this.loading = false
          this.setDetail(res.data)
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取下一条详情
    getNextDetail() {
      this.loading = true
      apiInnerEditGetNext(this.tableQuery)
        .then((res) => {
          this.loading = false
          this.resetForm()
          this.setDetail(res.data)
          this.tableQuery.position++
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 设置详情数据
    setDetail(data) {
      for (let key in this.formData) {
        if (data[key] !== null) {
          this.formData[key] = data[key]
        }
      }
      this.formData.id = data.id
      if (data.sheng_id) {
        this.areaSelected = []
        this.areaSelected.push(data.sheng_id)
        if (data.shi_id) {
          this.areaSelected.push(data.shi_id)
        }
      }
      this.$refs.tinymce.setValue(this.formData.desc)
    },
    // 获取下拉数据
    getSelectList() {
      this.$store.dispatch('select/getCityList').then((res) => {
        res.forEach((sheng) => {
          sheng.children.forEach((shi) => {
            delete shi.children
          })
        })
        this.areaList = res
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.areaSelected = []
      this.$refs.tinymce.reset()
      if (this.editModel === 'edit') {
        this.formData.id = ''
      }
    },
    // 提交
    handleSubmit(type) {
      this.$refs['elForm'].validate((valid, message) => {
        if (!valid) {
          const name = Object.keys(message)[0]
          this.$message.error(message[name][0].message)
          this.$nextTick(() => {
            const el = document.querySelectorAll('.el-form-item__error')[0]
            el.scrollIntoView({ block: 'center', behavior: 'smooth' })
          })
          return
        }
        this.loading = true
        if (this.editModel === 'add') {
          apiInnerAdd(this.formData)
            .then((res) => {
              this.loading = false
              this.$message({
                message: '发布成功',
                type: 'success',
              })
              setTimeout(() => {
                if (type === 'next') {
                  this.resetForm()
                } else {
                  this.handleClose()
                }
              }, 1000)
            })
            .catch(() => {
              this.loading = false
            })
        } else if (this.editModel === 'edit') {
          apiInnerEdit(this.formData)
            .then((res) => {
              this.loading = false
              this.$message({
                message: '发布成功',
                type: 'success',
              })
              setTimeout(() => {
                if (type === 'next') {
                  this.getNextDetail()
                } else {
                  this.handleClose()
                }
              }, 1000)
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    // 取消
    handleClose() {
      if (this.editModel === 'edit') {
        window.close()
      } else {
        this.$bus.$emit('innerNoticeListUpdate')
        this.$bus.$emit('closeSelectedTag', this.$route)
      }
    },
    // 删除
    handleDelete() {
      window.enterPreventDefault = false
      this.$confirm('确认要删除这条信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          window.enterPreventDefault = true
          apiInnerDel({ ids: [this.queryId] }).then(() => {
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
            setTimeout(() => {
              this.handleClose()
            }, 1000)
          })
        })
        .catch(() => {
          window.enterPreventDefault = true
        })
    },
    // 选择地区
    handleAreaChange(value) {
      this.formData.sheng_id = value[0] || ''
      this.formData.shi_id = value[1] || ''
    },
  },
}
</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 1.2;
}
.panel1 {
  padding-bottom: 70px;
}
.fixed-container {
  position: fixed;
  right: 0;
  bottom: 0;
  width: calc(100% - 140px);
  padding: 0 10px;
  z-index: 100;
  .panel-container {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    padding: 6px;
    margin: 0;
  }
}
.panel2 {
  padding-bottom: 70px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.panel-content {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
